#!groovy
import groovy.json.JsonOutput
import groovy.json.JsonSlurper



node (params.nodeLabel) {
    def status = 0
    def tomcatHome = params.tomcatHome
    def tomcatWebPath = tomcatHome + '/webapps'
    def bakPath = tomcatHome + '/app-bak'
    println(params.action)
    if('deploy' == params.action){
        download(status)
        deployPackage(tomcatHome,tomcatWebPath,bakPath,status)
        verifyApp(status)
    }else if('rollback'== params.action){
        rollBackForWar(tomcatWebPath,bakPath,tomcatHome)
    }else if('start' == params.action){
        actionStartTomcat(tomcatHome)
    }else if('stop' == params.action){
        actionStopTomcat(tomcatHome)
    }else {
        println('No Action Not Found...')
    }
}

def download(status){
    stage('Pull Artifact') {
        try {
            echo " Pull Artifact ${params.app}-${params.tag} PackageName: ${params.packageName}"
            sh """
              curl ${params.nexusRepos}/${params.app}/${params.tag}/${params.app}-${params.tag}.${params.packageType} -o ${params.packageName}.${params.packageType}  
           """
            status = 30011 //拉取成功
            notifyDeployCentral(status)
        }catch (exc) {
            echo 'Pull Artifact error !'
            status = 30010 //拉取失败
            notifyDeployCentral(status)
            throw exc
        }
    }
}

def bakArtifactForWar(tomcatWebPath,bakPath){
    stage('Bak Artifact') {
        try {
            echo "Bak Artifact"
            def warCount = sh(script: "ls -l ${tomcatWebPath} | grep ${params.packageName}.${params.packageType} |wc -l",returnStdout: true).trim()
            println("warCount: "+warCount)
            if((warCount as Integer) > 0){
                sh "ls ${tomcatWebPath} | grep war > bakResult"
                def bakByte = sh(script: 'ls -l | grep bakResult | awk \'{print $5}\'',returnStdout: true).trim()
                if((bakByte as Integer) > 0){
                    //def bakResults = readFile('bakResult').split("\r?\n")
                     sh """
                        mkdir -p ${bakPath}
                        cp ${tomcatWebPath}/${params.packageName}.${params.packageType} ${bakPath}
                        chown -R tomcat:tomcat ${bakPath}
                        ls ${bakPath}
                    """
                }
            }
        }catch (e){
            echo 'BakArtifact Error !'
            throw e
        }
    }
}

def deployPackage(tomcatHome,tomcatWebPath,bakPath,status){
    stage('Deploy Package'){
        try {
            echo "Deploy Package"
            if ('war' == params.packageType){
                stopTomcat(tomcatHome)
                bakArtifactForWar(tomcatWebPath,bakPath)
                copyWarToTomcat(tomcatWebPath)
                startTomcat(tomcatHome)
            }else if('jar' == params.packageType){
                //stopApp("${params.app}")
                println(" start app ... ")
            }
            status = 30051 //部署成功
            notifyDeployCentral(status)
        }catch (exc) {
            echo 'Deploy Artifact error !'
            status = 30050 //部署失败
            notifyDeployCentral(status)
            throw exc
        }
    }
}

def verifyApp(status) {
    stage('Verify App'){
        try{
            if(params.appCheckUrl){
                sleep 20
                echo "check done"
                def ips = sh(script: "ip addr | grep 'scope global' | awk '{print \$2}'",returnStdout: true).trim()
                println ips
                def ip = ips.substring(0,ips.indexOf("/"))
                println ip
                def resp = httpRequest(url:"http://${ip}:${params.appPort}${params.appCheckUrl}",timeout: 90)
                println('Status: '+resp.status)
            }
                status = 30061 //部署成功
                notifyDeployCentral(status)
        }catch (exc) {
            echo 'Verify Artifact error !'
            status = 30060 //部署失败
            notifyDeployCentral(status)
            throw exc
        }
    }
}

def notifyDeployCentral(status){
    stage("Notify DeployCentral"){
        echo "Notify DeployCentral: "+status
        def ips = sh(script: "ip addr | grep 'scope global' | awk '{print \$2}'",returnStdout: true).trim()
        println ips
        def ip = ips.substring(0,ips.indexOf("/"))
        def response = httpRequest(url:"${params.callBackHost}/deploy-central/prod/jenkins/notify?callBackId=${params.callBackId}&status=${status}&buildId=${BUILD_ID}&action=${JOB_NAME}@${params.nodeLabel}@${ip}",timeout: 10)
        println('Status: '+response.status)
    }
}

def stopTomcat(tomcatHome){
    println("---- Stop Tomcat ----")
    def pid = sh(script: "ps -ef | grep -w ${tomcatHome} | grep -v grep | awk '{print \$2}'",returnStdout: true).trim()
    echo 'Tomcat pid: '+ pid
    if(null != pid && "" != pid){
        sh "kill ${pid}"
    }
    sleep 5
}

def startTomcat(tomcatHome){
    def pid = sh(script: 'ps -ef | grep -w tomcat | grep -v grep | awk \'{print $2}\'',returnStdout: true).trim()
    def fid = sh(script: "ls ${tomcatHome}/bin/CATALINA_PID | grep -v grep | wc -l",returnStdout: true).trim()
    echo 'Tomcat pid: '+ pid
    echo 'CATALINA_PID: '+ fid
    if(null == pid || "" == pid){
    println("---- startTomcat ----:"+tomcatHome)
        script{
            withEnv(['JENKINS_NODE_COOKIE=dontkillme']) {
                sh """
                su - tomcat -c \"${tomcatHome}/bin/startup.sh\"
              """
                sleep 5
                if(fid as int == 1){
                    sh """
                      chown tomcat:tomcat ${tomcatHome}/bin/CATALINA_PID
                      chown -R tomcat:tomcat ${tomcatHome}/webapps/*
                      chown -R tomcat:tomcat ${tomcatHome}/logs/*
                    """
                }
            }
        }
    }else {
        echo 'Tomcat is starting... !'
    }
}

def copyWarToTomcat(tomcatWebPath){
    println("---- COPY ----:"+tomcatWebPath)
    sh """
    cp ${params.packageName}.${params.packageType} ${tomcatWebPath}
    """
}

def rollBackForWar(tomcatWebPath,bakPath,tomcatHome){
    try{
        stage('Stop Tomcat'){
            stopTomcat(tomcatHome)
        }
        stage('RollBack Artifact') {
            sh """
               cp ${bakPath}/*.war ${tomcatWebPath}
             """
            sh "ls ${tomcatWebPath}"
        }
        stage('Start Tomcat'){
            startTomcat(tomcatHome)
            sleep 20
        }
        stage('Verify App'){
            verifyApp(0);
        }
        notifyDeployCentral(16031) //回滚成功
    }catch (e){
        echo 'RollBackForWar Error !'
        notifyDeployCentral(16030) //回滚失败
        throw e
    }
}

def actionStartTomcat(tomcatHome){
    stage('Start App'){
        try{
            stage('Start App'){
                startTomcat(tomcatHome)
                sleep 20
            }
            stage('Verify App'){
                verifyApp(0);
            }
            notifyDeployCentral(16011)
        }catch (e){
            echo 'Start App Error !'
            notifyDeployCentral(16010)
            throw e
        }
    }
}

def actionStopTomcat(tomcatHome){
    stage('Stop App'){
        try{
            stopTomcat(tomcatHome)
            notifyDeployCentral(16021)
        }catch (e){
            echo 'Stop App Error !'
            notifyDeployCentral(16020)
            throw e
        }
    }
}